package com.house.service;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.house.dao.ImageMapper;
import com.house.entity.House;
import com.house.entity.Image;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;


/**
 * 图片模块服务层
 */
@Service
@Slf4j
public class ImageService extends ServiceImpl<ImageMapper, Image> {


    /**
     * 重置图片 目前用于房屋更新图片
     * @param relationId
     * @param images
     */
    public void reset(String relationId, List<String> images) {

        // 删除重新添加
        baseMapper.delete(Wrappers.<Image>query().eq("relation_id", relationId));

        images.forEach(imgStr -> {
            // 如果是图片路径，只取文件名保存
            if(imgStr.contains("/")) {
                imgStr = imgStr.substring(imgStr.lastIndexOf("/") + 1);
            }

            Image image = new Image();
            image.setImg(imgStr);
            image.setRelationId(relationId);
            image.setCreateTime(DateUtil.now());
            image.setUpdateTime(DateUtil.now());
            super.save(image);
        });

//        baseMapper.delete(Wrappers.<Image>query().eq("relation_id", ""));
    }



    @Autowired
    HouseService houseService;

    /**
     * 生成测试数据
     */
    public void createTestData() {
        List<House> houses = houseService.list();
        Random rand = new Random();
        for(House house : houses) {
            this.reset(house.getId(), INIT_IMAGE_MAP.get(rand.nextInt(INIT_IMAGE_MAP.size()) + 1));
        }
    }

    Map<Integer, List<String>> INIT_IMAGE_MAP = new HashMap<Integer, List<String>>(){{
        put(1, new ArrayList<String>(){{
            add("1-1.jpg");
            add("1-2.jpg");
            add("1-3.jpg");
            add("1-4.jpg");
            add("1-5.jpg");
        }});

        put(2, new ArrayList<String>(){{
            add("2-1.jpg");
            add("2-2.jpg");
            add("2-3.jpg");
            add("2-4.jpg");
            add("2-5.jpg");
        }});
    }};

}
